<template>
  <div class="top">
    <van-search v-model="value" placeholder="请输入搜索关键词"/>
    <div class="navigation">
      <div
          v-for="(item, index) in items"
          :key="index"
          class="navigation-item"
          :class="{ active: index === activeIndex }"
          @click="activeIndex = index"
          ref="itemRefs"
      >
        {{ item }}
      </div>
      <div
          class="navigation-underline"
          :class="{ active: activeIndex !== -1 }"
          :style="underlineStyle"
          ref="underlineRef"
      ></div>
      <van-icon class="collection" name="star-o" color="#ffd21e" size="20px" @click="">收藏</van-icon>
    </div>
  </div>
  <div class="main">
<!--    如果activeIndex为0,加载recommend组件-->
    <div v-if="activeIndex === 0">
      <recommend/>
    </div>
    <div v-else-if="activeIndex === 1">
      <shoe/>
    </div>
    <div v-else-if="activeIndex === 2">
      <dress/>
    </div>
    <div v-else="activeIndex === 3">
      <accessory/>
    </div>
  </div>
</template>

<script setup lang="ts">
import {useRoute,useRouter} from "vue-router";
import {ref, reactive, watch, onMounted} from 'vue'
import recommend from "@/components/shop-recommend.vue"
import accessory from "@/components/shop-accessory.vue"
import dress from "@/components/shop-dress.vue"
import shoe from "@/components/shop-shoe.vue"
import {showToast} from "vant";

const route = useRoute()
const router= useRouter()
const active = ref(0);
const value = ref('');
const activeIndex = ref(0);
const items = ref(["推荐", "鞋子", "服饰", "配件"]);
const underlineStyle = ref({
  transform: "translateX(0)",
})
const itemRefs = ref([]);
const underlineRef = ref(null);

const updateUnderline = () => {
  // 获取标题的宽度，减去下划线的宽度除以2，可以使下划线在标题下居中显示
  const item = itemRefs.value[activeIndex.value];
  const underline = underlineRef.value;
  let newLeft = Number((item.offsetWidth - underline.offsetWidth)) / 2;
  if (item && underline) {
    const {offsetLeft} = item;
    console.log(offsetLeft);
    underlineStyle.value = {
      transform: `translateX(${offsetLeft + newLeft}px)`,
    };
  }
};

watch(activeIndex, () => {
  updateUnderline();
});

onMounted(() => {
  updateUnderline();
});
</script>

<style scoped>
.top {
  position: fixed;
  width: 100%;
  height: 50px;
  top: 0px;
  left: 0px;
  z-index: 999;
}

.navigation {
  width: 250px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  position: relative;
  padding: 0px;
  height: 50px;
  font-size: 16px;
  font-weight: bold;
}

.navigation-item {
  cursor: pointer;
}

.navigation-item.active {
  color: #f00;
}

.navigation-underline {
  /* 下划线的宽度 */
  width: 50px;
  height: 3px;
  border-radius: 2px;
  position: absolute;
  bottom: 0;
  left: 0;
  background-color: #f00;
  transition: all 0.3s ease-in-out;
}

.navigation-underline.active {
  transform: translateY(-3px);
}

.collection{
  position: fixed;
  right: 10px;
  top: 70px;
  font-size:1rem;
}
</style>